import { v4 as uuid } from "uuid";

import {
  ADD_FILE_OR_FOLDER,
  REMOVE_FILE_OR_FOLDER,
  UPDATE_CLIP_FILE_OR_FOLDER,
  OPENED_FILEIDS_ADD,
  OPENED_FILEIDS_DELETE,
  UPDATE_ACTIVE_FILE_ID,
  UPDATE_FILE_OR_FOLDERNAME,
  PASTE_FILE_OR_FOLDER,
  UPDATE_COPY_ID,
} from "../constant";

/**
 * @param {string} name 添加文件名称
 * @param {string} folderId 待添加文件的文件夹uuid
 * @param {object} globalState 全局状态，从UI组件传递过来，对象传递引用
 * @param {boolean} bFile 添加的是文件还是文件夹,默认文件
 * @param {boolean} bPaste 是否是粘贴文件（夹），还是新建文件，默认粘贴
 * @param {string} pasteFileOrFolderId 粘贴文件或者文件夹
 */
export const addFileOrFolder = (
  name,
  folderId,
  globalState,
  bFile = true,
  bPaste = false,
  pasteFileOrFolderId = ""
) => {
  if (bFile) {
    //文件
    //有可能是复制粘贴的文件，也有可能是新增的文件
    if (bPaste) {
      //粘贴文件
      //1、根据id查询到指定的文件数据并且为其重新生成uuid，pid指向folderId即可
      const objOri = globalState.filesObj[pasteFileOrFolderId];
      return {
        type: ADD_FILE_OR_FOLDER,
        payload: {
          bFile,
          id: uuid(),
          name,
          content: objOri.content,
          pid: folderId,
        },
      };
    } else {
      //新建文件,添加到redux中
      return {
        type: ADD_FILE_OR_FOLDER,
        payload: {
          bFile,
          id: uuid(),
          name,
          content: `${name}的内容，只读`,
          pid: folderId,
        },
      };
    }
  } else {
    //文件夹
    if (bPaste) {
      //粘贴
    } else {
      //新建文件夹
      return {
        type: ADD_FILE_OR_FOLDER,
        payload: {
          bFile,
          id: uuid(),
          name,
          pid: folderId,
        },
      };
    }
  }
};
/**
 * 打开某个文件
 * @param {string} id 文件id
 */
export const addOpenFile = (id) => ({
  type: OPENED_FILEIDS_ADD,
  payload: id,
});
/**
 *关闭某个文件
 * @param {string} id 文件id
 */
export const removeOpenFile = (id) => ({
  type: OPENED_FILEIDS_DELETE,
  payload: id,
});
/**
 * 更新tabs中正在编辑的tab的id
 * @param {string} id 文件id
 */
export const updateActiveFileId = (id) => ({
  type: UPDATE_ACTIVE_FILE_ID,
  payload: id,
});
/**
 * 文件或者文件夹重命名
 * @param {string} id 文件（夹）标识符
 * @param {*} type 类型
 * @param {*} name 新的名称
 */
export const updateFileOrFolderName = (id, type, name) => ({
  type: UPDATE_FILE_OR_FOLDERNAME,
  payload: { id, type, name },
});
/**
 * 删除文件或者文件夹
 * @param {string} id 文件（夹）唯一标识
 */
export const removeFileOrFolder = (id) => ({
  type: REMOVE_FILE_OR_FOLDER,
  payload: id,
});
/**
 * 更新剪切板
 * @param {string} id 文件（夹）id
 */
export const updateClip = (id) => ({
  type: UPDATE_CLIP_FILE_OR_FOLDER,
  payload: id,
});
/**
 * 更新复制的id
 * @param {string} id 文件（夹）id
 */
export const updateCopyId = (id) => ({
  type: UPDATE_COPY_ID,
  payload: id,
});
/**
 * 粘贴文件或者文件夹
 * @param {string} pid 被粘贴的文件夹id
 */
export const pasteFileOrFolder = (pid) => ({
  type: PASTE_FILE_OR_FOLDER,
  payload: pid,
});
